package grpcs

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
	grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
	"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

type ClientOptionConfig struct {
	Logger *zap.Logger
}

func DefaultOptions() []grpc.DialOption {
	return []grpc.DialOption{grpc.WithInsecure()}
}

// 获取默认的grpc 配置
func DefaultClientOptions(config ClientOptionConfig) []grpc.DialOption {
	options := []grpc.DialOption{grpc.WithInsecure()}
	options = append(options, grpc.WithChainUnaryInterceptor(grpc_middleware.ChainUnaryClient(
		func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {

			token, ok := ctx.Value(auths.TOKEN_KEY).(*string)
			newCtx := ctx
			if ok && token != nil {
				md := metautils.ExtractOutgoing(ctx)
				newMd := md.Clone()
				newMd.Add("Authorization", *token)
				newCtx = newMd.ToOutgoing(ctx)
			}
			return invoker(newCtx, method, req, reply, cc, opts...)
		},
		grpc_zap.UnaryClientInterceptor(config.Logger),
		grpc_opentracing.UnaryClientInterceptor(),
	)))
	return options
}
